package com.demo.shiro.common;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;

/**
 * ShiroUtils
 */
public class ShiroUtils {

	public static void init(Ini config) {
		init(new IniSecurityManagerFactory(config));
	}

	public static void init(String iniResourcePath) {
		init(new IniSecurityManagerFactory(iniResourcePath));
	}

	public static void init(Factory<SecurityManager> factory) {
		SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
	}

	public static Subject login(String username, String password) throws AuthenticationException {
		Subject currentUser = SecurityUtils.getSubject();
//		if (!currentUser.isAuthenticated()) {
			// 创建 token
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			// 登录
			currentUser.login(token);
//		}
		return currentUser;
	}

	public static void logout() {
		SecurityUtils.getSubject().logout();
	}
}
